<template>
  <div class="tp h-full flex flex-col">
    <Header />

    <Content class="flex-1 overflow-auto">
      <div class="cp">
        <div class="card">
          <div class="c-title mt-2"> 基本信息 </div>

          <div class="line"></div>

          <div class="c-body">
            <BasicForm @register="registerForm1" />
          </div>
        </div>

        <div class="card">
          <div class="c-body" style="padding-top: 0">
            <BasicTable
              @register="registerTable"
              :dataSource="state.dataSource"
              :scroll="{ y: 320 }"
              style="margin: 0 -2px"
            >
              <template #tableTitle>
                <div class="c-title"> 商品明细 </div>
              </template>

              <template #toolbar>
                <a-flex gap="middle" align="center" justify="flex-end">
                  <a-button type="link" @click="onAdd"
                    >添加商品
                    <template #icon>
                      <PlusOutlined />
                    </template>
                  </a-button>
                </a-flex>
              </template>

              <template #action="{ record }">
                <TableAction
                  :divider="true"
                  :actions="[
                    {
                      color: 'success',
                      label: '删除',
                      popConfirm: {
                        title: '您确定要删除吗',
                        confirm: () => onDelete(record),
                      },
                    },
                  ]"
                />
              </template>
            </BasicTable>
          </div>
        </div>
      </div>
    </Content>

    <Footer class="">
      <a-flex align="center" justify="center" gap="middle" class="f-body">
        <a-button @click="router.back()"> 取消</a-button>

        <a-popconfirm title="您确定要入库吗" ok-text="确定" cancel-text="取消" @confirm="onSubmit">
          <a-button type="primary">确定入库 </a-button>
        </a-popconfirm>
      </a-flex>
    </Footer>
  </div>
</template>

<script setup>
  import { defineOptions, h, onActivated, onMounted, reactive, ref } from 'vue';

  import { BasicTable, TableAction, useTable } from '@/components/Table';

  import Header from '@/widget/header.vue';
  import Content from '@/widget/content.vue';
  import { POST } from '@/api/http';
  import { moveTypeCodeList } from '@/api/ds';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useRouter } from 'vue-router';
  import { BasicForm, useForm } from '@/components/Form';
  import ProImgCell from '@/widget/pro-img-cell.vue';
  import { InputNumber } from 'ant-design-vue';
  import Footer from '@/widget/footer.vue';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { copy, isNil } from '@/api/util.js';

  defineOptions({ name: 'StockIn' });

  const router = useRouter();

  const { createMessage } = useMessage();

  const state = reactive({ dataSource: [] });

  const [registerForm1, form1] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24, style: { paddingRight: '36px' } },

    schemas: [
      {
        label: '入库原因',
        field: 'moveTypeCode',
        required: true,
        component: 'Select',
        componentProps: {
          options: moveTypeCodeList.filter((o) => o.category === 'S'),
        },
        colProps: {
          span: 24,
        },
        itemProps: {
          wrapperCol: {
            span: 6,
          },
        },
      },

      {
        label: '备注',
        field: 'logNote',
        required: false,
        component: 'InputTextArea',
        componentProps: {
          maxlength: 100,
        },
        colProps: {
          span: 24,
        },
        itemProps: {
          wrapperCol: {
            span: 10,
          },
        },
      },
    ],
    showActionButtonGroup: false,
  });

  const first = ref(true);

  onMounted(() => {
    window._inProduct_ = null;
  });

  onActivated(() => {
    if (first.value) {
      first.value = false;
      return;
    }

    let { _inProduct_ } = window;

    if (_inProduct_) {
      state.dataSource = _inProduct_.P;
      window._inProduct_ = null;
    }
  });

  const [registerTable] = useTable({
    pagination: false,
    columns: [
      {
        title: '商品名称',
        dataIndex: 'goodsName',
        ellipsis: false,
        width: 290,
        customRender: ({ value: title, record }) =>
          h(ProImgCell, { src: record.goodsImage, title }),
      },
      {
        title: '规格',
        dataIndex: 'specs',
        ellipsis: false,
      },

      {
        title: '实收货数量',
        dataIndex: 'qty',
        ellipsis: false,
        customRender: ({ value, record }) => {
          return h('div', null, [
            h(InputNumber, {
              value,
              min: 0,
              max: 9999999,
              style: { width: '160px !important' },
              addonAfter: record.saleUnit || '',
              precision: 0,
              ['onUpdate:value']: (nVal) => {
                record.qty = nVal;
              },
            }),
          ]);
        },
      },
    ],
    useSearchForm: false,
    showTableSetting: false,
    bordered: true,
    showIndexColumn: false,
    rowKey: 'goodsSn',
  });

  const formList = [form1];

  async function onSubmit() {
    await Promise.all(formList.map((f) => f.validate()));
    const formData = formList.reduce((prev, f) => Object.assign(prev, f.getFieldsValue()), {});

    //保存
    const { moveTypeCode } = formData;
    const data = { ...formData };
    data.moveType = moveTypeCodeList.find((o) => o.value === moveTypeCode)?.category;
    data.detailList =
      state.dataSource?.map(({ goodsSn, qty }) => ({
        goodsSn,
        qty,
      })) ?? [];

    const { dataSource } = state;
    if (dataSource.length < 1) {
      createMessage.error(`商品明细不能为空`);
      return;
    }

    for (const { goodsName, qty } of dataSource) {
      if (isNil(qty) || qty < 1) {
        createMessage.error(`请输入“${goodsName}”实收货数量`);
        return;
      }
    }

    await POST('/product/productStoreOrDeliver', data);
    createMessage.success('已完成入库');
    await router.back();
  }

  function onAdd() {
    const { dataSource } = state;
    window._inProduct_ = copy({ P: dataSource });
    router.push('/stock/list/in/product');
  }

  function onDelete({ goodsSn }) {
    const { dataSource } = state;
    const index = dataSource.findIndex((o) => o.goodsSn === goodsSn);

    if (index > -1) {
      dataSource.splice(index, 1);
    }
  }
</script>
<style lang="less" scoped>
  .card {
    margin-bottom: 24px;
    padding: 12px;

    .c-title {
      color: #333;
      font-size: 14px;
      font-weight: 500;
    }

    .line {
      margin: 0 -12px;
      padding-bottom: 8px;
      border-bottom: 1px solid #f0f0f0;
    }

    .c-body {
      padding: 8px 12px;
    }
  }
</style>
